﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entities;

public partial class Admin_EditProduct : System.Web.UI.Page
{
    ProductManager proMan = new ProductManager();
    SupplierManager supMan = new SupplierManager();
    CategoryManager cateMan = new CategoryManager();
    Product pro;
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (!IsPostBack)
        {
            loadSupplier();
            loadCategory();
            int id = Convert.ToInt32(Request.QueryString["id"].ToString());
            LoadProductByID(id);
        }

    }

    public void LoadProductByID(int id)
    {
        pro = proMan.GetProductById(id);
        lblID.Text = pro.ProductID.ToString();
        txtName.Text = pro.ProductName;
        txtPrice.Text = pro.ProductPrice.ToString();
        txtQuantity.Text = pro.Quantity.ToString();
        txtUnit.Text = pro.Unit;
        txtDecription.Text = pro.Decription;
        ddlCategory.SelectedValue = pro.CategoryID.ToString();
        ddlSupplier.SelectedValue = pro.SupplierID.ToString();
        //flImage.
        imgProduct.ImageUrl = pro.imageLink;
    }

    public void loadSupplier()
    {
        ddlSupplier.DataSource = supMan.AllSupplier();
        ddlSupplier.DataValueField = "SupplierID";
        ddlSupplier.DataTextField = "CompanyName";
        ddlSupplier.DataBind();
    }

    public void loadCategory()
    {
        ddlCategory.DataSource = cateMan.AllCategory();
        ddlCategory.DataValueField = "CategoryID";
        ddlCategory.DataTextField = "CategoryName";
        ddlCategory.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("AdminProduct.aspx");
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            pro.ProductName = txtName.Text;
            pro.ProductPrice = Convert.ToDecimal(txtPrice.Text);
            pro.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue);
            pro.SupplierID = Convert.ToInt32(ddlSupplier.SelectedValue);
            pro.Quantity = Convert.ToInt32(txtQuantity.Text);
            pro.Unit = txtUnit.Text;
            pro.Decription = txtDecription.Text;
            string sPath = Server.MapPath("~/web.config");
            sPath = sPath.Substring(0, sPath.LastIndexOf("web.config"));
            pro.imageLink = "~/Images/Products/" + flImage.FileName;
            proMan.EditProduct(pro);
        }
        catch (Exception ex)
        {
            Session["Error"] = ex.Message;

        }

    }
}